package com.stlm2.controller;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectRequest;
import com.stlm2.util.ImageUtil;
import com.stlm2.util.StringUtils;
import com.stlm2.util.UploadImage;
import com.stlm2.util.codecontent.CodeContent;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.File;

/**
 * Author: fuchunyu
 * Date: 2017/6/19
 * Description：artEditor富文本专用上传接口
 */
@Controller
@RequestMapping("/image")
public class UploadImageController {
    @ResponseBody
    @RequestMapping("/uploadImage.json")
    public String test(String filed,ModelMap model ){

        //System.out.println(filed);

        if(StringUtils.isNullOrEmpty(filed)){
            return  CodeContent.getModelByCode(0,"请上传图片！",model);
        }

        String endpoint = "http://oss-cn-beijing.aliyuncs.com";
        String accessKeyId = "LTAIrLdK8OYw20F7";
        String accessKeySecret = "KfH2x72p6zFxbfKqC3kECzwOwFnHAK";
        String bucketName = "ddw-image";
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        String fileName= UploadImage.getFileName()+".png";
        try {
            File file = File.createTempFile(UploadImage.getFileName(), ".png");
            file.deleteOnExit();
            File file1= ImageUtil.decodeBase64ToImage(filed,file.getPath(),fileName);
            client.putObject(new PutObjectRequest(bucketName, fileName,file1));
            file.delete();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            client.shutdown();
        }
        model.put("path",UploadImage.ImagePath+fileName);
        return  CodeContent.getModelByCode(1,null,model);
    }


}
